package io.bdmc.modules.bss.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.bdmc.common.annotation.SysLogger;
import io.bdmc.common.utils.R;
import io.bdmc.modules.bss.entity.DeviceRoute;
import io.bdmc.modules.bss.entity.DeviceRouteGroup;
import io.bdmc.modules.bss.service.IDeviceRouteGroupService;
import io.bdmc.modules.bss.service.IDeviceRouteService;
import io.bdmc.modules.sys.controller.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 路由组 前端控制器
 * </p>
 *
 * @author 黄露
 * @since 2021-05-21
 */

// "路由组", description = "路由组")
@RestController
@RequestMapping("/bss/route/group")
public class DeviceRouteGroupController extends AbstractController {

	@Autowired
	IDeviceRouteGroupService _deviceroutegroupSvs;

	@Autowired
	IDeviceRouteService routeService;

	@GetMapping("/list")
	// "分页查询路由组", notes = "分页查询路由组")
	public R list() {
		return R.ok();

	}

	@GetMapping("/info")
	// "查询路由组", notes = "查询路由组")
	public R list(int routeGroupId) {
		return R.ok().putData(_deviceroutegroupSvs.getById(routeGroupId));
	}

	@SysLogger("新增路由组")
	@PostMapping("/add")
	// "新增路由组", notes = "新增路由组")
	public R add(@RequestBody DeviceRouteGroup deviceroutegroup) {
		deviceroutegroup.setCreateBy(getUser().getUsername());
		deviceroutegroup.setCreateTime(LocalDateTime.now());
		deviceroutegroup.setDeptId(getDeptId().intValue());
		Boolean b = deviceroutegroup.insert();
		return R.trueOrFalse(b);
	}

	@SysLogger("修改路由组")
	@PostMapping("/update")
	// "修改路由组", notes = "修改路由组")
	public R update(@RequestBody DeviceRouteGroup deviceroutegroup) {
		Boolean b = deviceroutegroup.updateById();
		return R.trueOrFalse(b);
	}

	@SysLogger("删除路由组")
	@PostMapping("/delete")
	// "删除路由组", notes = "删除路由组")
	public R delete(@RequestBody Integer routeGroupId) {
		if (routeGroupId > 0){
			final long count = routeService.count(new LambdaQueryWrapper<DeviceRoute>().eq(DeviceRoute::getGroupId, routeGroupId));
			if(count>0){
				return R.error("请先删除路由组下的子路由，再删除路由组。");
			}
			_deviceroutegroupSvs.removeById(routeGroupId);
		}
		return R.ok();
	}

	@GetMapping("tree")
	public R tree() {
		List<HashMap<String, Object>> map = _deviceroutegroupSvs.routeTree(getDeptId().intValue());
		return R.ok().putData(map);
	}
}
